package tcp.utils;

import exception.CustomException;
import parser.ReadState;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

public class StreamUtils {
    /*
    Java Socket 读写参考：https://blog.csdn.net/u011082160/article/details/100779231
     */
    public static byte[] readStream(ByteArrayOutputStream output, InputStream inStream, int timeout, ReadState state) throws IOException, CustomException {
        int alreadyRead = readStreamWithRecursion(output, inStream,timeout);
        output.close();
        int size = output.size();
        state.alreadyRead = alreadyRead;
        return output.toByteArray();
    }


    public static int readStreamWithRecursion(ByteArrayOutputStream output, InputStream inStream, int timeout) throws IOException, CustomException {
        long start = System.currentTimeMillis();
        while (inStream.available() == 0) {
            if ((System.currentTimeMillis() - start) >timeout) {//超时退出
                throw new CustomException("读取超时");
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }
        }
        byte[] buffer = new byte[2048];
        int read = inStream.read(buffer);
        output.write(buffer, 0, read);
        int wait = readWait();
        long startWait = System.currentTimeMillis();
        boolean checkExist = false;
        while (System.currentTimeMillis() - startWait <= wait) {
            int a = inStream.available();
            if (a > 0) {
                checkExist = true;
                //            LogUtils.w("========还有剩余：" + a + "个字节数据没读");
                break;
            }

        }
        if (checkExist) {
            read += readStreamWithRecursion(output, inStream, timeout);
        }
        return read;
    }

    /**
     * 二次读取最大等待时间，单位毫秒
     */
    public static int readWait() {
        return 100;
    }

    public static byte[] bufferToBytesArray(ByteBuffer byteBuffer) {
        byte[] ret = new byte[byteBuffer.limit()];
        int size = byteBuffer.limit();
        for (int i=0;i<size;i++) {
            ret[i] = byteBuffer.get();
        }
        return ret;
    }
}
